"use client";

import ordersService from "@/app/services/orders.service";
import userService from "@/app/services/user.service";
import Modal from "@/components/modal/modal";
import { formatDateToCustom } from "@/lib/date";
import Order, { OrderStatus } from "@/shared/order";
import User from "@/shared/user";
import { useContext, useEffect, useState } from "react";
import { UserCtx } from "../layout";
import { useRouter } from "next/navigation";
import { useNotifications } from "@/app/hooks/notification.hook";

export default function MePage() {
  const { showSuccess } = useNotifications();
  const router = useRouter();
  const [loading, setLoading] = useState(true);

  const [lastClicked, setLastClicked] = useState<number>(0);
  const [isOpen, setIsOpen] = useState(false);

  const openModal = () => setIsOpen(true);
  const closeModal = () => setIsOpen(false);
  const { user, setUser } = useContext(UserCtx);
  const [orders, setOrders] = useState<Order[]>([]);

  useEffect(() => {
    userService.getMe().then((user) => {
      setUser(user as User);
    });

    ordersService.getMyOrders().then((orders) => {
      setOrders(orders);
      setLoading(false);
    });
  }, []);

  const coloredStatus = (status: string) => {
    switch (status) {
      case "PROCESSING":
        return <span style={{ color: "orange" }}>В обработке</span>;
      case "PREPARING":
        return <span style={{ color: "#d3ad7f" }}>Сбор</span>;
      case "DELIVERY":
        return <span style={{ color: "#d3ad7f" }}>Передан в доставку</span>;
      case "COMPLETED":
        return <span style={{ color: "olive" }}>Завершен</span>;
    }
  };

  const handleSignOut = () => {
    localStorage.removeItem("token");
    router.push("/sign-in");
    showSuccess("Вы успешно вышли из системы");
  };

  if (loading)
    return (
      <section style={{ display: "flex", flex: 2, width: "100%" }}>
        <span style={{ margin: "0 auto" }} className="loader"></span>
      </section>
    );

  return (
    <section className="me" id="me" style={{ flex: 2 }}>
      <h1 className="heading">
        Профиль{" "}
        <span
          style={{ cursor: "pointer" }}
          onClick={handleSignOut}
          className="fa fa-sign-out"
        ></span>
      </h1>
      <div>
        <h1>
          Привет, <span className="colored">{user?.name}</span>!
        </h1>
        <span>
          Email: <h1 className="colored">{user?.email}</h1>
        </span>
        <span>
          Номер телефона: <h1 className="colored">{user?.phone}</h1>
        </span>
        <span>
          Роль:
          <h1 className="colored">
            {user?.role.toString() == "USER" ? "Пользователь" : "Администратор"}
          </h1>
        </span>
      </div>

      <h1 className="heading" style={{ marginTop: "50px" }}>
        История <span>заказов</span>
      </h1>
      <table className="ordersTable">
        <thead>
          <tr>
            <th>№</th>
            <th>Статус</th>
            <th>Дата заказа</th>
            <th>Адрес</th>
            <th>Кол-во позиций</th>
            <th>Сумма</th>
            <th>Кол-во персон</th>
            <th>Описание</th>
            <th>Позиции</th>
          </tr>
        </thead>
        <tbody>
          {orders.map((o) => (
            <tr>
              <td>{o.id}</td>
              <td>{coloredStatus(o.status.toString())}</td>
              <td>{formatDateToCustom(new Date(o.createdAt))}</td>
              <td>{o.address}</td>
              <td>{o.productCount}</td>
              <td>{o.sum} руб.</td>
              <td>{o.count}</td>
              <td>{o.description}</td>
              <td style={{ textAlign: "center" }}>
                <span
                  onClick={() => {
                    setLastClicked(o.id);
                    openModal();
                  }}
                  style={{ cursor: "pointer", fontSize: "25px" }}
                  className="fa fa-cutlery"
                ></span>
              </td>
            </tr>
          ))}
        </tbody>
      </table>
      {isOpen && <Modal orderId={lastClicked} onClose={closeModal} />}
    </section>
  );
}
